package com.hspedu.newData.dmsxl.树.转换题;
/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-05-15 
 * @Version: 1.0
 */

public class LC426将二叉树转换为排序的双向链表 {

    class Node {
        public int val;
        public Node left;
        public Node right;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val,Node _left,Node _right) {
            val = _val;
            left = _left;
            right = _right;
        }
    };

    Node head;
    Node pre;

    public Node treeToDoublyList(Node root) {

        if (root == null) return head;
        dfs(root);
        head.left = pre;
        pre.right = head;
        return head;
    }

    public void dfs(Node cur){
        if (cur == null) return;

        dfs(cur.left);
        if (pre == null){
            head = cur;
            pre = head;
        }else {
            pre.right = cur;
            cur.left = pre;
            pre = cur;
        }
        dfs(cur.right);
    }
}
